#include "table_widget.h"
#include <QDebug>

RowHoverDelegate::RowHoverDelegate(QTableWidget *tableWidget, QObject *parent)
    : QStyledItemDelegate(parent)
{

}

void RowHoverDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const
{
    QStyledItemDelegate::initStyleOption(option, index);

    if(isHoveredRow(*option, index)){
        option->state |= QStyle::State_MouseOver;
    }
}

bool RowHoverDelegate::isHoveredRow(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    bool ret       = false;
    int  gridWidth = 0;
    if(const QTableView* tableView = qobject_cast<const QTableView*>(option.widget)){
        gridWidth = tableView->showGrid() ? 1 : 0;
    }

    for(int i = 0; i < index.model()->columnCount(); ++i){
        QModelIndex idx = index.model()->index(index.row(), i);
        if(const QAbstractItemView* view = qobject_cast<const QAbstractItemView*>(option.widget)){
            /** 视图矩形必须包含网格线宽度，否则判断会异常 */
            QRect rect = view->visualRect(idx).adjusted(0, 0, gridWidth, gridWidth);
            if(rect.contains(view->viewport()->mapFromGlobal(QCursor::pos()))){
                ret = true;
            }
        }
    }

    return ret;
}


TableWidget::TableWidget(QWidget *parent) : QTableWidget(parent)
{
    RowHoverDelegate *delegate = new RowHoverDelegate(this, parent);
    setItemDelegate(delegate);
}
